const fs =  require('fs');
const game = require('./game')
const express = require('express')

var playerWinCount = 0;
var lastPlayerAction = null;
var sameCount = 0;

const app = express();

app.get('/favicon.ico',function(request,response){
    response.status(200);
    return;
})

app.get('/game',
    function(request,response,next){
        if(sameCount==9||playerWinCount>=3){
            response.status(500);
            response.send('我不和你玩了');
            return;
        }
        //involve next middleware
        next();
        if(response.playWon){
            playerWinCount++;
        }
    },

    function(request,response,next){
        const query = request.query;
        const playAction = query.action;

        if(!playAction){
            response.status(400);
            response.send();
            return;
        }
        if(lastPlayerAction == playAction){
            sameCount++
            if(sameCount>=3){
                response.status(500);
                response.send('你作弊，我再也不和你玩了');
                sameCount = 9;
                return;
            }
        }
        else{
            sameCount =0;
        }
        lastPlayerAction = playAction;
        response.playerAction = playAction
        next();
    },

    function(request,response){
        const playAction = response.playerAction;
        const  result = game(playAction);
        response.status(200);
        if(result === 0){
            response.send('平局，可以啊!');
        } else if(result === -1){
            response.send('你输了,回去再练练吧！');
        }else{
            response.send('你厉害，你赢了!')
            response.playWon = true;
        }
    }

)

app.get('/',function(request,response){
    response.send(
        fs.readFileSync(__dirname+'/game.html','utf-8')
    )
})

app.listen(4000)